<template>
  <div class="container">
    <Menu></Menu>
    <div class="box">
      <div class="box-main">
        <div class="box-main-top">
          <div class="box-main-top-btns">
            <t-space>
              <div>
                <t-button theme="primary" variant="base">发动态</t-button>
                <t-button style="margin-left: 8px" variant="outline" @click="router.push('/editor')">写文章</t-button>
              </div>
              <div class="box-main-top-btns-hello">
                <butterfly style="margin-right: 3px" theme="outline" size="24" fill="#e851b3" />
                {{ timeState }} {{ userInfo.nickName }}~
              </div>
            </t-space>
          </div>
          <div class="box-main-top-content">
            <t-textarea
              v-model="addArticleDTO.articleContent"
              placeholder="别社恐了，来聊天~"
              name="description"
              :autosize="{ minRows: 4, maxRows: 8 }"
              style="background-color: #f0f2f5"
            />
          </div>
          <img v-if="inputImg" class="box-main-top-content-img" :src="inputImg" alt="" />
          <div v-if="inputCategorys.length > 0" class="box-main-top-content-categorys">
            <div class="box-main-top-content-categorys-item"><BookmarkIcon /><span>已选分类</span></div>
            <div
              v-for="(categoroyName, index) in inputCategorys"
              :key="index"
              class="box-main-top-content-categorys-item"
            >
              <BookmarkIcon /><span style="position: relative"
                >{{ categoroyName }}
                <div class="del" @click="reduceCategory(categoroyName)">×</div>
              </span>
            </div>
          </div>
          <div v-if="inputLabels.length > 0" class="box-main-top-content-labels">
            <div class="box-main-top-content-labels-item"><ArtboardIcon /><span>已选话题</span></div>
            <div v-for="(labelName, index) in inputLabels" :key="index" class="box-main-top-content-labels-item">
              <ArtboardIcon /><span style="position: relative"
                >{{ labelName }}
                <div class="del" @click="reduceLabel(labelName)">×</div>
              </span>
            </div>
          </div>
          <div class="box-main-top-bottom">
            <div class="box-main-top-bottom-left">
              <div style="height: 32px; width: 45.6px" class="box-main-top-bottom-left-item">
                <t-upload
                  :headers="{
                    Authorization: Authorization,
                    id: userId,
                  }"
                  theme="file"
                  action="http://localhost:1023/oss/save"
                  @success="handleSuccess"
                >
                  <ImageIcon /><span>图片</span>
                </t-upload>
              </div>
              <div class="box-main-top-bottom-left-item">
                <t-dropdown :hide-after-item-click="false" placement="bottom" trigger="click" :min-column-width="288">
                  <t-button variant="text" style="padding: 0"> <ArtboardIcon /><span>话题</span> </t-button>
                  <template #dropdown>
                    <t-dropdown-menu>
                      <t-dropdown-item>
                        <t-input placeholder="查找话题" clearable>
                          <template #suffixIcon>
                            <SearchIcon />
                          </template>
                        </t-input>
                      </t-dropdown-item>
                      <t-dropdown-item
                        v-for="label in labels"
                        :key="label.leiId"
                        :value="label.leiId"
                        :disabled="label.isSelected"
                        @click="addLabel(label)"
                      >
                        <div style="display: flex; justify-content: space-between">
                          <div><ArtboardIcon /> {{ label.labelName }}</div>
                          <div>0&nbsp;讨论</div>
                        </div>
                      </t-dropdown-item>
                    </t-dropdown-menu>
                  </template>
                </t-dropdown>
              </div>
              <div class="box-main-top-bottom-left-item">
                <t-dropdown :hide-after-item-click="false" placement="bottom" trigger="click" :min-column-width="288">
                  <t-button variant="text" style="padding: 0"> <BookmarkIcon /><span>分类</span> </t-button>
                  <template #dropdown>
                    <t-dropdown-menu>
                      <t-dropdown-item>
                        <t-input placeholder="查找分类" clearable>
                          <template #suffixIcon>
                            <SearchIcon />
                          </template>
                        </t-input>
                      </t-dropdown-item>
                      <t-dropdown-item
                        v-for="category in categorys"
                        :key="category.leiId"
                        :value="category.leiId"
                        :disabled="category.isSelected"
                        @click="addCategory(category)"
                      >
                        <div style="display: flex; justify-content: space-between">
                          <div><BookmarkIcon /> {{ category.categoryName }}</div>
                          <div>0&nbsp;讨论</div>
                        </div>
                      </t-dropdown-item>
                    </t-dropdown-menu>
                  </template>
                </t-dropdown>
              </div>
            </div>
            <t-button class="box-main-top-bottom-btn" theme="primary" shape="round" variant="base" @click="addArticle"
              >发布</t-button
            >
          </div>
        </div>
        <div class="box-main-content">
          <t-tabs
            :default-value="1"
            drag-sort
            :value="tabValue"
            :scroll-position="'auto'"
            @drag-sort="onDragend"
            @change="onTabChange"
          >
            <t-tab-panel
              v-for="data in panelData"
              :key="data.value"
              :value="data.value"
              :label="data.label"
              :draggable="data.draggable"
            >
              <!-- 文章列表 -->
              <t-skeleton :loading="articleLoading" animation="gradient">
                <div v-for="article in articleList" :key="article.leiId" class="box-main-content-item">
                  <div class="box-main-content-item-top">
                    <img
                      v-if="article.avatar"
                      class="box-main-content-item-top-avatar"
                      :src="article.avatar"
                      alt=""
                      @click="goUser(article.createdBy)"
                    />
                    <img
                      v-else
                      class="box-main-content-item-top-avatar"
                      src="../../assets/datou.jpg"
                      alt=""
                      @click="goUser(article.createdBy)"
                    />
                    <div class="box-main-content-item-top-right">
                      <div class="box-main-content-item-top-right-name">{{ article.nickname }}</div>
                      <div class="box-main-content-item-top-right-des">{{ article.introduction }}</div>
                    </div>
                  </div>
                  <div class="box-main-content-item-title">
                    {{ article.articleTitle }}
                  </div>
                  <div class="box-main-content-item-shit">
                    <div class="box-main-content-item-shit-content">
                      {{ article.articleContent }}
                    </div>
                    <img class="box-main-content-item-shit-img" :src="article.articleImage" alt="" />
                  </div>
                  <div v-if="article.labelInfos" class="box-main-content-item-topic">
                    <span v-for="(label, shit) in article.labelInfos.data" :key="shit">#{{ label.labelName }}</span>
                  </div>
                  <div class="box-main-content-item-bottom">
                    <div class="box-main-content-item-bottom-item" @click="like(article.leiId)">
                      <ThumbUp2Icon :class="article.isLiked ? 'like-active' : ''" size="18" /><span>
                        {{ article.likeCount }}
                      </span>
                    </div>
                    <div class="box-main-content-item-bottom-item" @click="showComment(article.leiId)">
                      <div
                        v-if="article.isShowComment"
                        style="color: #0052d9; font-size: 14px"
                        @click="addCommentDTO.articleId = null"
                      >
                        <ChatBubble1Icon size="18" /><span>收起评论</span>
                      </div>
                      <div v-else @click="showComment(key, article)">
                        <ChatBubble1Icon size="18" /><span>{{ article.comments ? article.comments.length : 0 }}</span>
                      </div>
                    </div>
                    <div class="box-main-content-item-bottom-item" @click="star(article.leiId)">
                      <HeartIcon :class="article.isStar ? 'star-active' : ''" size="18" /><span>
                        {{ article.starCount }}
                      </span>
                    </div>
                    <div class="box-main-content-item-bottom-item" @click="share(article.leiId)">
                      <Share1Icon :class="article.isShared ? 'share-active' : ''" size="18" /><span>{{
                        article.shareCount
                      }}</span>
                    </div>
                  </div>
                  <!-- 评论上方输入框 -->
                  <div v-if="article.isShowComment" class="box-main-content-item-comment">
                    <img
                      v-if="userInfo.avatar"
                      class="box-main-content-item-comment-avatar"
                      :src="userInfo.avatar"
                      alt=""
                    />
                    <img v-else class="box-main-content-item-comment-avatar" src="../../assets/datou.jpg" alt="" />
                    <div style="width: 80%">
                      <div class="box-main-content-item-comment-top-content">
                        <t-textarea
                          v-model="addCommentDTO.commentContent"
                          placeholder="别社恐了，来聊天~"
                          name="description"
                          :autosize="{ minRows: 3, maxRows: 8 }"
                        />
                      </div>
                      <div class="box-main-content-item-comment-top-bottom">
                        <div class="box-main-top-bottom-left">
                          <div class="box-main-top-bottom-left-item">
                            <ImageIcon /><span style="margin-left: 2px; margin-bottom: 0.24px">图片</span>
                          </div>
                        </div>
                        <t-button
                          class="box-main-top-bottom-btn"
                          theme="primary"
                          shape="round"
                          variant="base"
                          @click="addComment"
                          >发布</t-button
                        >
                      </div>
                    </div>
                  </div>
                  <!-- 评论 -->
                  <div v-if="article.isShowComment">
                    <div v-for="comment in article.comments" :key="comment.leiId" class="box-main-content-item-reply">
                      <div class="box-main-content-item-reply-top">
                        <img
                          v-if="comment.avatar"
                          class="box-main-content-item-reply-top-avatar"
                          :src="comment.avatar"
                          alt=""
                        />
                        <img
                          v-else
                          class="box-main-content-item-reply-top-avatar"
                          src="../../assets/datou.jpg"
                          alt=""
                        />
                        <div class="box-main-content-item-reply-top-des">
                          <div class="box-main-content-item-reply-top-des-name">{{ comment.nickName }}</div>
                          <div class="box-main-content-item-reply-top-des-time">2099年发布</div>
                        </div>
                      </div>
                      <div class="box-main-content-item-reply-shit">
                        <div class="box-main-content-item-reply-shit-content">{{ comment.commentContent }}</div>
                        <img class="box-main-content-item-reply-shit-img" :src="comment.imgUrl" />
                      </div>
                      <div class="box-main-content-item-reply-bottom">
                        <div class="box-main-content-item-reply-bottom-item">发布于1999年</div>
                        <div class="box-main-content-item-reply-bottom-item" @click="likeComment(comment)">
                          <ThumbUp2Icon :class="comment.isLiked ? 'like-active' : ''" size="18" /><span>
                            {{ comment.likeCount }}
                          </span>
                        </div>
                        <div
                          v-if="!comment.isShowReply"
                          class="box-main-content-item-reply-bottom-item"
                          @click="comment.isShowReply = !comment.isShowReply"
                        >
                          共有 {{ comment.replies.length }} 条回复
                        </div>
                        <div
                          v-else
                          class="box-main-content-item-reply-bottom-item"
                          style="color: #0052d9"
                          @click="comment.isShowReply = !comment.isShowReply"
                        >
                          收起回复
                        </div>
                      </div>
                      <div
                        v-if="comment.isShowReply"
                        style="margin-top: 10px"
                        class="box-main-content-item-reply-input"
                      >
                        <div v-if="article.isShowComment">
                          <div style="width: 80%; padding: 0 40px">
                            <div>
                              <t-textarea
                                v-model="addReplyDTO.replyContent"
                                :placeholder="'回复：@' + comment.nickName"
                                name="description"
                                :autosize="{ minRows: 3, maxRows: 8 }"
                              />
                            </div>
                            <div style="margin-top: 10px">
                              <t-button theme="primary" shape="round" variant="base" @click="addReply(comment.leiId)"
                                >发布</t-button
                              >
                            </div>
                          </div>
                        </div>
                      </div>
                      <div v-if="comment.isShowReply">
                        <div v-for="reply in comment.replies" :key="reply.leiId" class="box-main-content-item-reply">
                          <div class="box-main-content-item-reply-top">
                            <img
                              v-if="reply.avatar"
                              class="box-main-content-item-reply-top-avatar"
                              :src="reply.avatar"
                              alt=""
                            />
                            <img
                              v-else
                              class="box-main-content-item-reply-top-avatar"
                              src="../../assets/datou.jpg"
                              alt=""
                            />
                            <div class="box-main-content-item-reply-top-des">
                              <div class="box-main-content-item-reply-top-des-name">{{ reply.nickName }}</div>
                              <div class="box-main-content-item-reply-top-des-time">2099年发布</div>
                            </div>
                          </div>
                          <div class="box-main-content-item-reply-shit"></div>
                          <div class="box-main-content-item-reply-shit-content">{{ reply.replyContent }}</div>
                          <img class="box-main-content-item-reply-shit-img" :src="reply.imgUrl" />
                          <div class="box-main-content-item-reply-bottom" style="padding: 0 40px">
                            <div class="box-main-content-item-reply-bottom-item">发布于1999年</div>
                            <div class="box-main-content-item-reply-bottom-item" @click="likeReply(reply)">
                              <ThumbUp2Icon :class="reply.isLiked ? 'like-active' : ''" size="18" /><span>
                                {{ reply.likeCount }}
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <t-divider style="margin-bottom: 0"></t-divider>
              </t-skeleton>

              <t-button
                v-show="!isEnd"
                theme="default"
                variant="base"
                style="width: 100%; margin: 12px 0"
                @click="showMore"
                >点击查看更多</t-button
              >
            </t-tab-panel>
          </t-tabs>
        </div>
      </div>
      <div class="box-sider">
        <t-skeleton :loading="hotArticleLoading" animation="gradient">
          <div class="box-sider-sign">
            <div class="box-sider-sign-title">
              <butterfly theme="outline" size="24" fill="#e851b3" /><span style="margin: 0 6px">签到获取积分</span
              ><butterfly theme="outline" size="24" fill="#e851b3" />
            </div>
            <div class="box-sider-sign-content">
              <div class="box-sider-sign-content-city">{{ city }}</div>
              <div class="box-sider-sign-content-weather">
                <div class="box-sider-sign-content-weather-name">
                  <sunny theme="outline" size="16" fill="#333" /><span style="margin-left: 5px">{{
                    weather.weather
                  }}</span>
                </div>
                <div class="box-sider-sign-content-weather-wendu">{{ weather.temperature }}℃</div>
              </div>
              <t-button v-if="!isSign" class="box-sider-sign-content-btn" @click="sign">签到</t-button>
              <t-button v-else theme="default" class="box-sider-sign-content-btn">已签到</t-button>
            </div>
          </div>
        </t-skeleton>

        <t-skeleton :loading="hotArticleLoading" animation="gradient">
          <div class="box-sider-topic">
            <div class="box-sider-topic-top">
              <div class="box-sider-topic-top-item">
                <fire theme="outline" size="24" fill="#D54941" />
                <span class="box-sider-fire">热门文章</span>
              </div>
              <div class="box-sider-topic-top-item">
                <span style="color: #029cd4">更多</span>
                <double-right theme="outline" size="24" fill="#029CD4" />
              </div>
            </div>
            <div class="box-sider-topic-content">
              <div v-for="(item, index) in hotArticles" :key="index" class="box-sider-topic-content-item">
                <span class="box-sider-topic-content-item-name">{{
                  item.articleTitle ? item.articleTitle : item.articleContent
                }}</span>
                <span class="box-sider-topic-content-item-value">
                  <fire theme="outline" size="24" fill="#8B8B8B" />
                  <span>{{ item.articleFire }}</span>
                </span>
              </div>
            </div>
          </div>
        </t-skeleton>

        <t-skeleton :loading="hotLabelLoading" animation="gradient">
          <div class="box-sider-topic">
            <div class="box-sider-topic-top">
              <div class="box-sider-topic-top-item">
                <fire theme="outline" size="24" fill="#D54941" />
                <span class="box-sider-fire">热门话题</span>
              </div>
              <div class="box-sider-topic-top-item">
                <span style="color: #029cd4">更多</span>
                <double-right theme="outline" size="24" fill="#029CD4" />
              </div>
            </div>
            <div class="box-sider-topic-content">
              <div v-for="(item, index) in hotLabels" :key="index">
                <div v-if="item.labelName" class="box-sider-topic-content-item">
                  <span class="box-sider-topic-content-item-name"># {{ item.labelName }}</span>
                  <span class="box-sider-topic-content-item-value">
                    <fire theme="outline" size="24" fill="#8b8b8b" />
                    <span>{{ item.labelFire }}</span>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </t-skeleton>

        <t-skeleton :loading="hotCategoryLoading" animation="gradient">
          <div class="box-sider-topic">
            <div class="box-sider-topic-top">
              <div class="box-sider-topic-top-item">
                <fire theme="outline" size="24" fill="#D54941" />
                <span class="box-sider-fire">热门分类</span>
              </div>
              <div class="box-sider-topic-top-item">
                <span style="color: #029cd4">更多</span>
                <double-right theme="outline" size="24" fill="#029CD4" />
              </div>
            </div>
            <div class="box-sider-topic-content">
              <div v-for="(item, index) in hotCategorys" :key="index">
                <div v-if="item.categoryName" class="box-sider-topic-content-item">
                  <span class="box-sider-topic-content-item-name">{{ item.categoryName }}</span>
                  <span class="box-sider-topic-content-item-value">
                    <fire theme="outline" size="24" fill="#8b8b8b" />
                    <span>{{ item.categoryFire }}</span>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </t-skeleton>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import AMapLoader from '@amap/amap-jsapi-loader';
import { Butterfly, DoubleRight, Fire, Sunny } from '@icon-park/vue-next';
import {
  ArtboardIcon,
  BookmarkIcon,
  ChatBubble1Icon,
  HeartIcon,
  ImageIcon,
  SearchIcon,
  Share1Icon,
  ThumbUp2Icon,
} from 'tdesign-icons-vue-next';
import { MessagePlugin, TabsProps, UploadProps } from 'tdesign-vue-next';
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import {
  addArticleApi,
  addCommentApi,
  addReplyApi,
  getCategoryByIdsApi,
  getCommentApi,
  getHotArticleApi,
  getHotCategoryApi,
  getHotLabelApi,
  getLabelByIdsApi,
  getReplyApi,
  likeArticleApi,
  likeCommentApi,
  likeReplyApi,
  queryCategoryApi,
  queryLabelApi,
  searchArticleApi,
  shareArticleApi,
  starArticleApi,
} from '@/api/article';
import { getCity, getWeather } from '@/api/map';
import { getUrlApi } from '@/api/oss';
import { getUserByIdApi, signApi } from '@/api/user';
import Menu from '@/components/Menu.vue';

onMounted(() => {
  AMapLoader.load({
    key: '27b3a6a6945acce9aa1bdbf9926eeae5', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [], // 在这里配置后不生效，why？
  })
    .then(async (AMap) => {
      const res = await getCity();
      city.value = res.data.city;
      const result = await getWeather(city.value);
      weather.value = result.data.lives[0];
    })
    .catch((e) => {
      console.log(e);
    });
});

const router = useRouter();
// 当前城市的天气
const weather = ref({});
// 当前城市
const city = ref('');
// 热门文章骨架屏状态
const hotArticleLoading = ref(true);
const hotCategoryLoading = ref(true);
const hotLabelLoading = ref(true);
// 文章列表骨架屏状态
const articleLoading = ref(true);
// 文件上传中请求头携带的内容
const Authorization = `Bearer${localStorage.getItem('token')}`;
const userId = ref(localStorage.getItem('id'));
// 判断是否还有文章
const isEnd = ref(false);
// 输入框关联分类名称
const inputCategorys = ref([]);
// 输入框关联话题名称
const inputLabels = ref([]);
// 输入框上传的文件地址
const inputImg = ref('');
// 输入框上传文件后返回的key值
const fileKey = ref('');
// 文章列表
const articleList = reactive([]);
// tab栏索引
const tabValue = ref<TabsProps['value']>('0');
// 防止用户多次点击导致多次请求
const throttle = ref(false);
// tab栏id
const tabId = ref('');
const hotArticles = ref([]);
const hotCategorys = ref([]);
const hotLabels = ref([]);
const userInfo = ref({
  id: localStorage.getItem('id'),
  avatar: '',
  nickName: '',
});
// 点赞收藏转发参数
const addCountDTO = ref({
  articleId: '',
  isLiked: null,
  isStar: null,
  isShared: null,
});
// 发布文章参数
const addArticleDTO = ref({
  articleContent: '',
  nickname: '一只呆瓜',
  categoryIds: [],
  labelIds: [],
  articleImage: '@/assets/datou.jpg',
});
// 条件分页查询分类参数
const queryCategoryDTO = ref({
  categoryName: '',
  categoryIds: [],
  current: 1,
  pageSize: 100,
});
// 条件分页查询标签参数
const queryLabelDTO = ref({
  labelName: '',
  labelIds: [],
  current: 1,
  pageSize: 10,
});
// 条件分页查询文章参数
const searchArticleDTO = ref({
  input: '',
  categoryId: null,
  current: 1,
  pageSize: 10,
});
// 发布评论参数
const addCommentDTO = ref({
  articleId: '',
  commentContent: '',
});
// 查询评论参数
const queryCommentDTO = ref({
  articleId: '',
  current: 1,
  pageSize: 10,
});
// 点赞评论参数
const likeCommentDTO = ref({
  commentId: '',
  isLiked: 0,
});
// 新增回复参数
const addReplyDTO = ref({
  commentId: '',
  replyContent: '',
});
// 点赞回复参数
const likeReplyDTO = ref({
  replyId: '',
  isLiked: 0,
});
// tab栏数据
const panelData = ref([]);
// 话题下拉框
const labels = ref([]);
// 分类下拉框
const categorys = ref([]);
// 当前时间段
const timeState = ref('上午');
// 是否签到
const isSign = ref(false);

// 签到
const sign = async () => {
  const res = await signApi(userId.value);
  isSign.value = !res.data;
};
sign();

// 判断当前是上午还是下午
function getTimeState() {
  // 获取当前时间
  const timeNow = new Date();
  // 获取当前小时
  const hours = timeNow.getHours();
  // 设置默认文字
  let state = ``;
  // 判断当前时间段
  if (hours >= 0 && hours <= 10) {
    state = `早上好，`;
  } else if (hours > 10 && hours <= 13) {
    state = `中午好，`;
  } else if (hours > 13 && hours <= 18) {
    state = `下午好，`;
  } else if (hours > 18 && hours <= 24) {
    state = `晚上好，`;
  }
  return state;
}
timeState.value = getTimeState();

// 拖拽tab栏
const onDragend: TabsProps['onDragSort'] = ({ currentIndex, targetIndex }) => {
  [panelData.value[currentIndex], panelData.value[targetIndex]] = [
    panelData.value[targetIndex],
    panelData.value[currentIndex],
  ];
};

// 切换tab栏
const onTabChange: TabsProps['onChange'] = (newValue) => {
  searchArticleDTO.value.current = 1;
  tabValue.value = newValue;
  panelData.value.forEach(async (item, index) => {
    if (tabValue.value === index.toString()) {
      if (tabValue.value === '0' || tabValue.value === '1') {
        searchArticleDTO.value.categoryId = null;
        getArticleList();
      } else {
        tabId.value = item.leiId;
        searchArticleDTO.value.categoryId = tabId.value;
        getArticleList();
      }
    }
  });
};

// 获取文章列表
const getArticleList = async () => {
  let res = {};
  try {
    res = await searchArticleApi(searchArticleDTO.value);
    if (res.data.length < 10) {
      isEnd.value = true;
    }
  } catch (error) {
    console.log(error);
  }
  if (searchArticleDTO.value.categoryId != null) {
    articleList.length = 0;
    res.data.forEach((item) => {
      articleList.push(item);
    });
  } else {
    articleList.push(...res.data);
  }
  articleList.forEach(async (item, index) => {
    item.likeCount = res.data[index].likeCount;
    item.starCount = res.data[index].starCount;
    item.shareCount = res.data[index].shareCount;
    item.isShowComment = false;
    item.categoryInfos = await getCategoryByIdsApi({ categoryIds: res.data[index].categoryIds });
    item.labelInfos = await getLabelByIdsApi({ labelIds: res.data[index].labelIds });
    getComment(item);
  });
  console.log(articleList);
  articleLoading.value = false;
};
getArticleList();

// 新增文章
const addArticle = async () => {
  // 节流处理
  if (throttle.value) {
    alert('你在搞什么飞机？！');
    return;
  }
  throttle.value = true;
  addArticleDTO.value.articleImage = inputImg.value;
  await addArticleApi(addArticleDTO.value);
  throttle.value = false;
  // 清空输入框参数
  addArticleDTO.value.articleContent = '';
  inputCategorys.value = [];
  inputLabels.value = [];
  inputImg.value = '';
  MessagePlugin.success('发布成功');
  router.go(0);
};

// 点击查看更多
const showMore = () => {
  searchArticleDTO.value.current += 1;
  getArticleList();
};

// 点击评论按钮
const showComment = (key, article) => {
  // 展示被点击文章的评论区
  articleList.forEach((item) => {
    if (item.leiId === key) {
      item.isShowComment = !item.isShowComment;
    }
  });
  addCommentDTO.value.articleId = article.leiId;
};

// 点赞按钮
const like = (key) => {
  articleList.forEach(async (item) => {
    if (item.leiId === key) {
      item.isLiked = !item.isLiked;
      addCountDTO.value.articleId = key;
      addCountDTO.value.isLiked = item.isLiked ? 1 : 0;
      await likeArticleApi(addCountDTO.value);
      item.likeCount += item.isLiked ? 1 : -1;
    }
  });
};

// 收藏按钮
const star = (key) => {
  articleList.forEach(async (item) => {
    if (item.leiId === key) {
      item.isStar = !item.isStar;
      addCountDTO.value.articleId = key;
      addCountDTO.value.isStar = item.isStar ? 1 : 0;
      await starArticleApi(addCountDTO.value);
      item.starCount += item.isStar ? 1 : -1;
    }
  });
};

// 转发按钮
const share = (key) => {
  articleList.forEach(async (item) => {
    if (item.leiId === key) {
      item.isShared = !item.isShared;
      addCountDTO.value.articleId = key;
      addCountDTO.value.isShared = item.isShared ? 1 : 0;
      await shareArticleApi(addCountDTO.value);
      item.shareCount += item.isShared ? 1 : -1;
    }
  });
};

// 分页查询所有分类
const queryCategory = async () => {
  const res = await queryCategoryApi(queryCategoryDTO.value);
  // 存入主页的tabs栏
  res.data.forEach((item, index) => {
    item.isSelected = false;
    panelData.value.push({
      leiId: item.leiId,
      value: `${index}`,
      label: item.categoryName,
      content: item.categoryName,
      draggable: true,
    });
  });
  // 存入分类下拉框
  categorys.value.push(...res.data);
};
queryCategory();

// 分页查询所有话题
const queryLabel = async () => {
  const res = await queryLabelApi(queryLabelDTO.value);
  res.data.forEach((item) => {
    item.isSelected = false;
  });
  // 存入话题下拉框
  labels.value.push(...res.data);
};
queryLabel();

// 输入框上传图片后成功的回调函数
const handleSuccess: UploadProps['onSuccess'] = (params) => {
  console.log('success', params.file.response);
  fileKey.value = params.file.response.fileKey;
  userId.value = params.file.response.createUser;
  getUrl();
  MessagePlugin.success('上传成功');
};

// 获取文件路径
const getUrl = async () => {
  const res = await getUrlApi(fileKey.value, userId.value);
  inputImg.value = res;
};

// 向输入框添加话题
const addLabel = (label) => {
  label.isSelected = true;
  inputLabels.value.push(label.labelName);
  addArticleDTO.value.labelIds.push(label.leiId);
};

// 向输入框添加分类
const addCategory = (category) => {
  category.isSelected = true;
  inputCategorys.value.push(category.categoryName);
  addArticleDTO.value.categoryIds.push(category.leiId);
};

// 输入框减少分类
const reduceCategory = (categoryName) => {
  inputCategorys.value.forEach((item, index) => {
    if (item === categoryName) {
      inputCategorys.value.splice(index, 1);
      addArticleDTO.value.categoryIds.splice(index, 1);
      // 下拉框中的选项变为可选
      categorys.value.forEach((item) => {
        if (item.categoryName === categoryName) {
          item.isSelected = false;
        }
      });
    }
  });
};

// 输入框减少话题
const reduceLabel = (labelName) => {
  inputLabels.value.forEach((item, index) => {
    if (item === labelName) {
      inputLabels.value.splice(index, 1);
      addArticleDTO.value.labelIds.splice(index, 1);
      // 下拉框中的选项变为可选
      labels.value.forEach((item) => {
        if (item.labelName === labelName) {
          item.isSelected = false;
        }
      });
    }
  });
};

// 获取热门文章
const getHotArticle = async () => {
  const res = await getHotArticleApi();
  hotArticles.value = res.data;
  hotArticleLoading.value = false;
};
getHotArticle();

// 获取热门分类
const getHotCategory = async () => {
  const res = await getHotCategoryApi();
  hotCategorys.value = res.data;
  hotCategoryLoading.value = false;
};
getHotCategory();

// 获取热门标签
const getHotLabel = async () => {
  const res = await getHotLabelApi();
  hotLabels.value = res.data;
  hotLabelLoading.value = false;
};
getHotLabel();

// 发布评论
const addComment = async () => {
  // 节流处理
  if (throttle.value) {
    alert('你在搞什么飞机？！');
    return;
  }
  throttle.value = true;
  await addCommentApi(addCommentDTO.value);
  throttle.value = false;
  addCommentDTO.value.commentContent = '';
  router.go(0);
};

// 获取当前文章的所有评论
const getComment = async (article) => {
  queryCommentDTO.value.articleId = article.leiId;
  const res = await getCommentApi(queryCommentDTO.value);
  article.comments = res.data;
  article.comments.forEach(async (item) => {
    item.isShowReply = false;
    item.replies = await getReply(item);
  });
};

// 点赞评论
const likeComment = async (comment) => {
  comment.isLiked = !comment.isLiked;
  likeCommentDTO.value.isLiked = comment.isLiked ? 1 : 0;
  likeCommentDTO.value.commentId = comment.leiId;
  await likeCommentApi(likeCommentDTO.value);
  comment.likeCount += comment.isLiked ? 1 : -1;
};

// 根据用户id查询用户信息
const getUserById = async () => {
  const res = await getUserByIdApi(userInfo.value.id);
  userInfo.value.avatar = res.data.avatar;
  userInfo.value.nickName = res.data.nickname;
};
getUserById();

// 点击文章列表的头像
const goUser = (id) => {
  router.push({ path: `/user/${id}` });
};

// 新增回复
const addReply = async (key) => {
  // 节流处理
  if (throttle.value) {
    alert('你在搞什么飞机？！');
    return;
  }
  throttle.value = true;
  addReplyDTO.value.commentId = key;
  await addReplyApi(addReplyDTO.value);
  throttle.value = false;
};

// 查询评论的回复
const getReply = async (comment) => {
  const res = await getReplyApi({ commentId: comment.leiId });
  return res.data;
};

// 点赞回复
const likeReply = async (reply) => {
  reply.isLiked = !reply.isLiked;
  likeReplyDTO.value.isLiked = reply.isLiked ? 1 : 0;
  likeReplyDTO.value.replyId = reply.leiId;
  reply.likeCount += reply.isLiked ? 1 : -1;
  await likeReplyApi(likeReplyDTO.value);
};
</script>

<style scoped lang="less">
@import './index.less';
</style>
